package com.autonavi.abs.common.logger;

import org.slf4j.Logger;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author wwy
 * @version V1.0
 * <p>Description: 日志脱敏</p>
 * @date 2020-07-23 12:18
 */
public class DecryptLogger extends LoggerDecorator {

    /**
     * 手机号
     */
    public static final Pattern MOBILE_PATTER = Pattern.compile("\\D{1}1\\d{10}\\D{1}$*");
    /**
     * 身份证
     */
    public static final Pattern CERTIFICATE_PATTER = Pattern.compile("\\D{1}([1-9])\\d{17}\\D{1}$*");

    public static final String MOBILE_REGEX = "(?<=\\d{3})\\d(?=\\d{3})";
    public static final String CERTIFICATE_REGEX = "(?<=\\d{3})\\d(?=\\d{3})";
    public static final String REPLACE_TEXT = "*";

    public DecryptLogger(Logger logger) {
        super(logger);
    }

    @Override
    public void debug(String s) {
        super.debug(filter(s));
    }

    @Override
    public void info(String s) {
        super.info(filter(s));
    }

    @Override
    public void warn(String s) {
        super.warn(filter(s));
    }

    @Override
    public void error(String s) {
        super.error(filter(s));
    }

    /**
     * 过滤日志内容
     *
     * @param text
     * @param pattern
     * @param regex
     * @param regexReplacement
     * @return
     */
    public static String doFilter(String text, Pattern pattern, String regex, String regexReplacement) {
        if (text == null || text.length() < 1) {
            return "";
        }
        Map<String, String> findMap = new HashMap<>();

        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            String key = matcher.group();
            key = key.substring(1, key.length() - 1);
            findMap.put(key, key.replaceAll(regex, regexReplacement));
        }

        for (String key : findMap.keySet()) {
            text = text.replaceAll(key, findMap.get(key));
        }
        return text;
    }

    /**
     * 脱敏，超过4k不脱敏
     *
     * @param text
     * @return
     */
    public static String filter(String text) {

        //超过4K长度的为了性能问题不进行加密
        if (text != null && text.length() <= 4096) {
            text = doFilter(text, MOBILE_PATTER, MOBILE_REGEX, REPLACE_TEXT);
            text = doFilter(text, CERTIFICATE_PATTER, CERTIFICATE_REGEX, REPLACE_TEXT);
        }

        return text;
    }
}
